package org.aplikator.client.shared.rpc.marshaller;

import org.aplikator.client.shared.descriptor.FunctionDTO;
import org.aplikator.client.shared.descriptor.PropertyDTO;
import org.jboss.errai.marshalling.client.api.MarshallingSession;
import org.jboss.errai.marshalling.client.api.annotations.ClientMarshaller;
import org.jboss.errai.marshalling.client.api.annotations.ServerMarshaller;
import org.jboss.errai.marshalling.client.api.json.EJObject;
import org.jboss.errai.marshalling.client.api.json.EJValue;
import org.jboss.errai.marshalling.client.marshallers.AbstractNullableMarshaller;

import java.util.List;

@ClientMarshaller(FunctionDTO.class)
@ServerMarshaller(FunctionDTO.class)
@SuppressWarnings("unchecked")
public class FunctionDTOMarshaller extends AbstractNullableMarshaller<FunctionDTO> {

	/*@Override
	public Class<FunctionDTO> getTypeHandled() {
		return FunctionDTO.class;
	}*/

	@Override
	public FunctionDTO[] getEmptyArray() {
		return new FunctionDTO[0];
	}

	@Override
	public FunctionDTO doNotNullDemarshall(EJValue o, MarshallingSession ctx) {
		if (o.isObject() != null) {
			EJObject ejObject = o.isObject();
			FunctionDTO fdto = new FunctionDTO();
			DemarshallingUtils.clientDescriptorBaseUnMarshall(ejObject, fdto);
			List listUnMarshall = DemarshallingUtils.listUnMarshall(ejObject.get("properties"), ctx, PropertyDTO.class.getName());
			fdto.setProperties(listUnMarshall);
			
			if (ejObject.containsKey("size")) {
				fdto.setSize(ejObject.get("size").isNumber().intValue());
			}
			return fdto;
		} else return null;
	}

	@Override
	public String doNotNullMarshall(FunctionDTO o, MarshallingSession ctx) {
		StringBuilder builder = new StringBuilder().append('{');
		MarshallingUtils.clientDescriptorBase(builder, o).append(',');
		MarshallingUtils.number("size", o.getSize(), builder).append(',');
		MarshallingUtils.key("properties", builder).append(':');
		MarshallingUtils.listMarshall(builder, o.getProperties(), ctx, PropertyDTO.class.getName());
		builder.append('}');
		return builder.toString();
	}
}
